/**
* @Author: fiyc
* @Date : 2019-04-19 16:42
* @FileName : command-handler.js
* @Description :
*     - 命令处理模块
*/

const Client = require('./mqtt-client');
const receiveDefaultConfig = require('./config/receive.json');
const sendDefaultConfig = require('./config/send.json');
const fs = require('fs');
const path = require('path');

const cwd = process.cwd();
const hander = {

    /**
     * 接受消息
     * @param {Object} config 配置参数 
     * @param {String} config.host MQTT连接地址
     * @param {Number} config.port MQTT连接端口
     * @param {String} config.username MQTT用户名
     * @param {String} config.password MQTT密码
     * @param {String} config.id 客户端ID
     * @param {boolean} config.clean 是否清除会话
     * @param {String} config.file 配置文件地址
     * @param {String} config.topic 主题
     */
    receive: function (config) {
        config = removeNoneParam(config);
        if (config.file) {
            let filePath = path.join(cwd, config.file);
            if (fs.existsSync(filePath)) {
                try {
                    config = require(filePath);
                } catch (error) {
                    console.error('无效的配置文件.');
                    return;
                }
            } else {
                console.error(`无法找到配置文件: ${filePath}`);
                return;
            }
        }

        const options = Object.assign(receiveDefaultConfig, config);
        new Client(options, function (client) {
            const topic = config.topic || "#";
            console.log(`[订阅主题] ${topic}`);
            client.subscribe(topic, { qos: 2 });
        });
    },


    /**
     * 发送消息
     * @param {Object} config 配置参数 
     * @param {String} config.host MQTT连接地址
     * @param {Number} config.port MQTT连接端口
     * @param {String} config.username MQTT用户名
     * @param {String} config.password MQTT密码
     * @param {String} config.id 客户端ID
     * @param {String} config.message 推送消息
     * @param {String} config.file 配置文件地址
     * @param {String} config.topic 主题
     */
    send: function (config) {
        config = removeNoneParam(config);
        if (config.file) {
            let filePath = path.join(cwd, config.file);
            if (fs.existsSync(filePath)) {
                try {
                    config = require(filePath);
                } catch (error) {
                    console.error(`无效的配置文件. ${error}`);
                    return;
                }
            } else {
                console.error(`无法找到配置文件: ${filePath}`);
                return;
            }
        }

        const options = Object.assign(sendDefaultConfig, config);
        if (!options.topic) {
            console.error("无效的主题信息.");
            return;
        }

        new Client(options, function (client) {
            if (config.message) {
                client.publish(options.topic, config.message);
                return;
            }

            if (!Array.isArray(options.messages) || options.messages.length == 0) {
                console.log("缺少发送消息");
                return;
            }

            let currentIndex = -1;
            let intervalFlag = setInterval(function () {
                const intervalType = Number(options.loopType) || 0; // 0: 顺序推送,  1: 顺序循环推送   2: 随机循环推送

                switch (intervalType) {
                    case 0:
                        currentIndex += 1;
                        if (currentIndex >= options.messages.length) {
                            clearInterval(intervalFlag);
                        }
                        break;

                    case 1:
                        currentIndex += 1;
                        if (currentIndex >= options.message.length) {
                            currentIndex -= options.message.length;
                        }

                        break;

                    case 2:
                        currentIndex = Math.floor(Math.random() * options.message.length);
                        break;
                    default:
                        currentIndex = Math.floor(Math.random() * options.message.length);
                        break;
                }

                client.publish(options.topic, JSON.stringify(options.messages[currentIndex]));

            }, Number(options.interval) || 3000);
        });

    },

    /**
     * 拷贝默认配置文件
     * @param {String} name 配置名 receive|send
     */
    copyConfig: function (name) {
        const defaultConfigPath = path.join(__dirname, 'config', `${name}.json`);
        const targetPath = path.join(cwd, `mqtt-cli-${name}-config.json`);
        fs.copyFileSync(defaultConfigPath, targetPath);
    }
};

const removeNoneParam = function (params) {
    if (!params) {
        return {};
    }

    for (let key in params) {
        if (params[key] === undefined) {
            delete params[key];
        }
    }

    return params;
}

module.exports = hander;